package com.bnzj.core.webflux.security;

import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;
import com.bnzj.core.util.JsonUtils;
import com.bnzj.core.web.constant.CommonWebEnum;
import org.apache.commons.codec.Charsets;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName WebfluxAccessDeniedHandler
 * @Description TODO
 * @Author
 * @Date 2019/9/10
 * @Version V1.0
 **/
public class WebfluxAccessDeniedHandler implements ServerAccessDeniedHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
        ResponseResult<?> responseResult = new ResponseResult<>(new ResultCode(CommonWebEnum.ACCESS_DENIED.getCode(), CommonWebEnum.ACCESS_DENIED.getMsg()));
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        DataBuffer buffer = response.bufferFactory().wrap(JsonUtils.objToJson(responseResult).getBytes(Charsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }
}
